package com.topInterview;

/**
 * @Author: huangzhigao
 * @Date: 2022/2/20 18:09
 */
public class Leecode79_SearchLetter {
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (process(board, i, j, word.toCharArray(), 0)) {
                    return true;
                }
            }
        }
        return false;
    }


    //从i,j位置，能不能找到从k~word.length的单词
    public boolean process(char[][] board, int i, int j, char[] word, int k) {
        if (k == word.length) {
            return true;
        }

        if (i < 0 || i == board.length || j < 0 || j == board[0].length) {
            return false;
        }

        if (board[i][j] != word[k]) {
            //当前值不等于word[k]
            return false;
        }
        //代表走过的路记为0，防止走回头路
        char tmp = board[i][j];
        board[i][j] = 0;
        boolean ans = process(board, i + 1, j, word, k + 1)
                || process(board, i - 1, j, word, k + 1)
                || process(board, i, j + 1, word, k + 1)
                || process(board, i, j - 1, word, k + 1);

        //最后在改回来
        board[i][j] = tmp;
        return ans;
    }
}
